package com.example.testuploadfile.download;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileDownloader {

    public static void downloadFile(String fileURL, String destinationFilePath) throws IOException {
        // 创建 URL 对象
        URL url = new URL(fileURL);

        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置请求方法为 GET
        connection.setRequestMethod("GET");

        // 设置一些常见的请求头
        connection.setRequestProperty("User-Agent", "Mozilla/5.0");

        // 获取文件的总大小
        int fileSize = connection.getContentLength();
        System.out.println("文件大小: " + fileSize/1024/1024+"MB");
        // 获取输入流，读取文件数据
        try (BufferedInputStream in = new BufferedInputStream(connection.getInputStream()); FileOutputStream fileOutputStream = new FileOutputStream(destinationFilePath); BufferedOutputStream out = new BufferedOutputStream(fileOutputStream)) {

            // 缓冲区大小
            byte[] buffer = new byte[4096];
            int bytesRead;
            long totalBytesRead = 0;

            // 用于记录上次打印的进度
            int lastProgress = 0;

            // 下载并写入文件
            while ((bytesRead = in.read(buffer)) != -1) {
                totalBytesRead += bytesRead;
                out.write(buffer, 0, bytesRead);

                // 计算当前进度百分比
                int progress = (int) ((totalBytesRead * 100) / fileSize);

                // 如果当前进度增加了10%或更多，才打印进度
                if (progress >= lastProgress + 10) {
                    lastProgress = progress;
                    System.out.println("下载进度: " + progress + "%");
                }
            }
        } finally {
            connection.disconnect();
        }
    }

    public static void main(String[] args) {
        String fileURL = "https://vdept3.bdstatic.com/mda-phak4iwqemb7sb20/cae_h264/1691771953798667157/mda-phak4iwqemb7sb20.mp4?v_from_s=hkapp-haokan-nanjing&auth_key=1737526250-0-0-67cb63f4ed95341be6fcddf52835e617&bcevod_channel=searchbox_feed&pd=1&cr=0&cd=0&pt=3&logid=0649968206&vid=9686610572091454305&klogid=0649968206&abtest="; // 目标文件的 URL
        String destinationFilePath = "downloaded_file.mp4"; // 下载后保存的文件路径

        try {
            long startTime = System.currentTimeMillis();
            downloadFile(fileURL, destinationFilePath);
            long endTime = System.currentTimeMillis();

            System.out.println("文件下载成功！总耗时: " + (endTime - startTime) / 1000 / 60 + "分钟");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件下载失败！");
        }
    }
}
